var express = require('express');
var router = express.Router();

const fs = require("fs");
const banner = require("../sql/banner");
const sql = require("../sql/sql");
const uuid = require("uuid");

/* GET home page. */
router.get('/', function(req, res, next) {
  sql.getData(banner).then((data)=>{
    if(req.session.isLogin === "ok" && req.session.power <= 1){
      res.render('banner', {
        index:2,
        power:req.session.power,
        data
      })
    }else{
      res.send("404 ： 未找到你要搜索的页面");
    }
  })
});

router.post('/addAction', function(req, res, next) {
  
  // res.send(req.body)
  // res.send(req.files)
  // let apath = req.files
  // // let apath = req.files.destination;
  // // let bpath = req.files.filenam;
  // // let cpath = req.files.originalname;
  // // res.send(apath[0].destination)
  // // res.send(apath[0].filenam);
  // let newName = apath[0].destination;
  // // res.send(req.protocol)
  // // res.send(req.hostname)
  // let path = req.protocol+"://"+req.hostname+":3000"+newName.replace("./public","")+"/"+apath[0].filename+"-"+apath[0].originalname;
  // res.send(path)
  // http://localhost:3000/public/uploads/asaff.jpg
  // req.files.forEach(val=>{

  // })
  req.files.forEach(val=>{
      // res.send(val)  //查看数据模式
  let oldName = val.path
  let newName = val.path+"-"+val.originalname;
  // res.send(newName)
    // 改名
  fs.renameSync(oldName, newName);
  // res.send(newName)
  // res.send(req.hostname)
  let path = req.protocol+"://"+req.hostname+":3000"+val.destination.replace("./public","")+"/"+val.filename+"-"+val.originalname;
    // res.send(path)
  sql.addData(banner,{
    bannerId:"banner-" + uuid.v1(),
    name:req.body.imgName,
    title:req.body.imgTitle,
    src:path,
    time:Date.now(),
    author:req.session.userName
  }).then(()=>{
    res.redirect("/banner")
  })
})
});


router.get('/del', function(req, res, next) {
  sql.delData(banner,{bannerId:req.query.id}).then(()=>{
    res.redirect("/banner")
  })
});


module.exports = router;
